package com.jxb.network;

import com.blankj.utilcode.util.GsonUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @author jinxb
 * date     : 2021/5/20
 * desc     :
 */
public class BaseRequestBean {
    public HashMap<String, String> toMap() {
        HashMap<String, String> map = new HashMap<>();
        try {
            Class<?> clazz = this.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object object = field.get(this);
                String value;
                if (object instanceof Integer) {
                    value = field.get(this) + "";
                } else if (object instanceof Float) {
                    value = field.get(this) + "";
                } else if (object instanceof Double) {
                    value = field.get(this) + "";
                } else if (object instanceof String) {
                    value = field.get(this) + "";
                } else if (object instanceof List) {
                    value = GsonUtils.toJson(field.get(this));
                } else if (object != null) {
                    value = GsonUtils.toJson(field.get(this));
                } else {
                    continue;
                }
                map.put(fieldName, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public String toJson() {
        return GsonUtils.toJson(this);
    }

    public RequestBody toJsonBody() {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        return RequestBody.create(JSON, toJson());
    }
}
